<?php

namespace app\admin\model\payment;

use think\Loader;
use think\Model;
use traits\model\SoftDelete;

class Channel extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'payment_channel';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text'
    ];
    

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }

    
    public function getStatusList()
    {
        return ['normal' => __('Status normal'), 'disabled' => __('Status disabled')];
    }
    
    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function getConfigAttr($value) {
        return json_decode($value, true);
    }

    protected function setConfigAttr($value) {
        if (is_array($value)) {
            return json_encode($value);
        }
        return $value;
    }

    /**
     * 获取当前订单服务类
     *
     * @return \addons\payment\library\ServiceInterface
     */
    public function getService() {
        $className = "\\addons\\payment\\library\\impl\\" . Loader::parseName($this->service, 1);
        if (!class_exists($className)) {
            $this->error = "不支持的支付服务";
            return false;
        }
        return new $className;
    }


}
